package com.xuecheng.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoThreadLocal;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mappers.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.order.utils.PayUtils;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author 七安
 * @since 2022-09-30
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private PayUtils payUtils;

    /**
     * 获取支付url
     *
     * @param orderNo 订单号
     * @return 结果
     */
    @Override
    public ResponseResult<String> getPayUrl(String orderNo) throws BusinessException {
        //判空
        if (orderNo == null) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //根据订单号查询订单表
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, AuthInfoThreadLocal.getUserId());
        wrapper.eq(Orders::getOrderNo, orderNo);
        Orders orders = ordersService.getOne(wrapper);
        //判断订单状态
        if (!OrdersConstants.ORDER_INIT_STATUS.equals(orders.getStatus())) {
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        //判断有无支付记录
        LambdaQueryWrapper<Payment> payWrapper = new LambdaQueryWrapper<>();
        payWrapper.eq(Payment::getOrderNo, orderNo);
        Payment payment = paymentMapper.selectOne(payWrapper);
        if (ObjectUtils.isNotEmpty(payment)) {
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        //构建支付记录
        payment = new Payment();
        //设置学生id
        payment.setUserId(AuthInfoThreadLocal.getUserId());
        //设置机构id
        payment.setCompanyId(orders.getCompanyId());
        //设置订单编号
        payment.setOrderNo(orderNo);
        //设置支付状态
        payment.setStatus(OrdersConstants.NOT_PAID.toString());
        //设置支付方式
        payment.setPayMethod(OrdersConstants.PAY_METHOD_WX);
        //设置支付金额
        payment.setTotalAmount(orders.getPrice().longValue());
        paymentMapper.insert(payment);
        //获取支付url
        String url = payUtils.createOrder(orderNo, payment.getTotalAmount(), orders.getCoursePubName());
        return ResponseResult.okResult(url);
    }
}
